<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="65%" append-to-body :before-close="closeDelDialog">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="审批事项" name="0">
          <div style="padding: 1%">
            <el-row :gutter="10" class="mb8" ref="refbut">
              <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-folder-delete"  v-show="isShow && approvalStatus == '1'" @click="CancelApproval">取消审批</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-success"  v-if="isShowButton && approvalStatus == '1'" @click="adopt">通过</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-error"   v-if="isShowButton && approvalStatus == '1'" @click="failed">不通过</el-button>
              </el-col>
            </el-row>

            <!-- 流程图 -->
            <el-image
              :style="{ width:'90%' }"
              :src="imageUrl"
              :preview-src-list="imageUrlList">
            </el-image>

            <el-table :data="tableDataList" border align="center" header-align="center" height="20%" :loading="loading" @cell-dblclick="handleClick">
              <el-table-column label="序号" type="index" width="55" align="center" />
              <el-table-column label="申请人" prop="creator" align="center"></el-table-column>
              <el-table-column label="档案门类" prop="categoryName" align="center"></el-table-column>
              <el-table-column label="题名" prop="title" align="center"></el-table-column>
              <el-table-column label="密级" prop="mjChange" align="center"></el-table-column>
              <el-table-column label="申请时间" prop="createTime" align="center"></el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="审批过程" name="1">
          <el-table :data="tableList" border align="center" header-align="center" height="600" :loading="tableloading">
            <el-table-column label="步骤" type="index" width="55" align="center" />
            <el-table-column label="任务节点" prop="activityName" align="center"></el-table-column>
            <el-table-column label="办理人" prop="assignee" align="center"></el-table-column>
            <el-table-column label="审批开始时间" prop="startTime" align="center"></el-table-column>
            <el-table-column label="审批结束时间" prop="endTime" align="center"></el-table-column>
            <el-table-column label="用时" prop="time" align="center"></el-table-column>
            <el-table-column label="审批意见" prop="isAgree" align="center"></el-table-column>
<!--            <el-table-column label="批注" prop="comment" align="center"></el-table-column>-->
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 取消审批页面 -->
    <el-dialog title="取消审批" :visible.sync="cancelopen" width="35%" append-to-body>
      <el-form ref="cancelForm" :model="cancelForm" :rules="cancelRules" label-width="120px">
        <el-form-item label="取消审批原因" prop="reason">
          <el-input v-model="cancelForm.reason" type="textarea" placeholder="请输入内容" style="width: 90%" ref="textareaRef" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen" :celldbData="celldbData"
                     @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
                     @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->
  </div>
</template>

<script>
import estimateTableHeight from "@/mixins/estimateTableHeight";
import {
  approvalList,
  cancel,
  endWorkFlowInstance, getProcessDateByInstanceId,
  getTable,
  searchApprovalBpmnBase64
} from "@/api/archive/archivalAppraisal/classification/examineApprove"
import {getLastIndexOf} from "@/utils";
import {getthbytreenodeHeaderList} from "@/api/archive/warehouseManagement/upDownShelves";
import jianDetailsOpen from "@/components/componentsJianDetails";
import juanDetailsOpen from "@/components/componentsJuanDetails";
import {getInfo} from "@/api/login";
import {formDataSave} from "@/api/archive/archiveBorrow/borrowReceipt";

export default {
  name: "detail",
  props: ["title","open","isType"],
  mixins: [estimateTableHeight], // 混入方法
  components: { jianDetailsOpen, juanDetailsOpen },
  data() {
    return {
      activeName: '0',
      tableList: [],
      tableloading: true,
      // 流程图地址
      flowchartUrl: '',
      imageUrl: '',
      imageUrlList: [],
      // 审批状态
      approvalStatus: '',
      tableDataList: [],
      loading: true,
      // 列表行信息
      info: {},
      user: {},
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      isShow: false,
      isShowButton: false,
      cancelopen: false,
      cancelForm: {
        reason: undefined
      },
      cancelRules: {
        reason: [
          { required: true, message: "取消审批原因不能为空", trigger: "blur" },
        ]
      },
      instanceId: '',
      noClick: true
    }
  },
  created() {
    this.getConfigKey("FLOWCHART_URL").then(response => {
      this.flowchartUrl = response.msg
    });
    getInfo().then(res => {
      this.user = res.user
    })
  },
  methods: {
    init(val) {
      console.log(val)
      // 代表从待办任务打开的
      if(this.isType == '1') {
        searchApprovalBpmnBase64(val.instanceId).then(resp=>{
          this.imageUrl = "data:image/png;base64,"+resp.data;
          this.imageUrlList = ["data:image/png;base64,"+resp.data];
        })
        //this.imageUrl = this.flowchartUrl + '?instanceId=' + val.instanceId
        this.instanceId = val.instanceId
        if(val.status == null) {
          this.approvalStatus = '1'
        }
        if(val.processVariables != null) {
          if(val.processVariables.creatorId == this.user.userId) {
            this.isShow = true
          }
        }
       // if(this.user.userName.includes('dagly')) {
          this.isShowButton = true
     //   }
        this.getTableList()
      } else if (this.isType == '2') { // 代表从已办任务打开的
        searchApprovalBpmnBase64(val.instanceId).then(resp=>{
          this.imageUrl = "data:image/png;base64,"+resp.data;
        })
        //this.imageUrl = this.flowchartUrl + '?instanceId=' + val.instanceId
        this.instanceId = val.instanceId
        if(val.status == null) {
          this.approvalStatus = '1'
        }
        // 隐藏按钮
        this.isShow = false
        this.isShowButton = false
        this.getTableList()
      } else {
        this.info = val
        this.instanceId = val.processInstance
        searchApprovalBpmnBase64(val.processInstance).then(resp=>{
          this.imageUrl = "data:image/png;base64,"+resp.data;
        })
        //this.imageUrl = this.flowchartUrl + '?instanceId=' + val.processInstance
        this.approvalStatus = val.state
        if(val.creatorId == this.user.userId) {
          this.isShow = true
        }
        if(this.user.userName.includes('dagly')) {
          this.isShowButton = true
        }
        this.getList()
      }
    },
    handleTabClick(tab, event) {
      if(tab.name == '1') {
        console.log(this.instanceId)
        getProcessDateByInstanceId(this.instanceId).then(response=>{
          this.tableloading = false
          this.tableList = []
          for (let i = 0; i < response.data.length; i++) {
            for (let j = 0; j < response.data[i].activityList.length; j++) {
              // console.log(response.data[i].activityList)
              var startTime = this.processingTime(response.data[i].activityList[j].startTime)
              var endTime = null
              var time = null
              if(response.data[i].activityList[j].endTime != null) {
                endTime = this.processingTime(response.data[i].activityList[j].endTime)
                time = this.calculateElapsedTime(startTime, endTime)
              }
              var isAgree = null
              if(response.data[i].activityList[j].isAgree != null) {
                isAgree = response.data[i].activityList[j].isAgree.deleteReason
              }
              var comment = null
              if(response.data[i].activityList[j].comment != null) {
                comment = response.data[i].activityList[j].comment.controlValue
              }
              this.tableList.push({
                startTime: startTime,
                endTime: endTime,
                time: time,
                activityName: response.data[i].activityList[j].activityName,
                assignee: response.data[i].activityList[j].assignee,
                isAgree: isAgree,
                comment: comment
              })
            }
          }
        })
      }
    },
    processingTime(time) {
      const date = new Date(time);
      // 获取日期的年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0');
      // 获取时间的小时、分钟、秒
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      // 构建日期时间字符串
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 计算用时
    calculateElapsedTime(startTime, endTime) {
      const start = new Date(startTime);
      const end = new Date(endTime);
      const diff = end - start; // 计算时间差，单位为毫秒

      const days = Math.floor(diff / (1000 * 60 * 60 * 24)); // 天
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 小时
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); // 分钟
      const seconds = Math.floor((diff % (1000 * 60)) / 1000); // 秒

      return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
    },
    getTableList() {
      const id = this.instanceId
      getTable(id).then(response=>{
        console.log(response)
        this.tableDataList = []
        this.tableDataList.push(response.data)
      })
    },
    getList() {
      const id = this.info.id
      approvalList(id).then(response=>{
        console.log(response.data)
        this.tableDataList = []
        this.tableDataList.push(response.data)
      })
    },
    // 取消审批
    CancelApproval() {
      this.resetForm('cancelForm')
      this.$nextTick(() => {
        this.$refs.textareaRef.$refs.textarea.style.height = 'auto'; // 重置高度
      });
      this.cancelopen = true
    },
    submit() {
      this.$refs["cancelForm"].validate(valid => {
        if(valid) {
          if(this.noClick) {
            this.noClick = false
            this.cancelForm.instanceId = this.info.processInstance
            endWorkFlowInstance(this.cancelForm).then(response=>{
              const id = this.info.id
              cancel(id).then(response=>{
                this.$modal.msgSuccess('取消审批成功')
                this.cancelopen = false
                this.$emit("closeDelDialog")
                setTimeout(() => {
                  this.noClick = true
                }, 300)
              }).catch(() => {
                setTimeout(() => {
                  this.noClick = true
                }, 300)
              })
            })
          }
        }
      })
    },
    cancel() {
      this.cancelopen = false
    },
    // 通过
    adopt() {
      if(this.noClick) {
        this.noClick = false
        var data = [{
          controlId: 'is_agree',
          controlDefault: '不同意--__--同意',
          controlIsParam: 'i',
          controlLable: '审批意见',
          controlType: 'radio',
          controlValue: 1
        }]
        data.id = this.tableDataList[0].taskId
        formDataSave(data).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.cancelopen = false
          this.$emit("closeDelDialog")
          setTimeout(() => {
            this.noClick = true
          }, 300)
        }).catch(() => {
          setTimeout(() => {
            this.noClick = true
          }, 300)
        })
      }
    },
    // 不通过
    failed() {
      if(this.noClick) {
        this.noClick = false
        var data = [{
          controlId: 'is_agree',
          controlDefault: '不同意--__--同意',
          controlIsParam: 'i',
          controlLable: '审批意见',
          controlType: 'radio',
          controlValue: 0
        }]
        data.id = this.tableDataList[0].taskId
        formDataSave(data).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.cancelopen = false
          this.$emit("closeDelDialog")
          setTimeout(() => {
            this.noClick = true
          }, 300)
        }).catch(() => {
          setTimeout(() => {
            this.noClick = true
          }, 300)
        })
      }
    },
    handleClick(row) {
      console.log(row)
      var level="";
      var type = "";
      if (getLastIndexOf(row.subTableName) == "F") {  //F 件
        level = 0
        type = "f"
      } else if (getLastIndexOf(row.subTableName) == "V") { //卷
        level = 1
        type = "v"
      } else { //项目
        level = 3
        type = "x"
      }
      this.form = {
        id: row.id,
        type: type
      }
      var categoryId = row.categoryId
      var menuId = this.$route.meta.menuId
      getthbytreenodeHeaderList(
        {
          categoryId: categoryId, menuId: menuId, subTableName: row.subTableName
        }
      ).then(response => {
        var tableHeaderList = response.rows;
        this.celldbData = {
          id: row.filesId,
          categoryId: categoryId,
          menuId: menuId,
          sub_table_name: row.subTableName,
          label: row.categoryName,
          level: level,
          ifSub_table_name: row.subTableName,
          isDel: "0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
          tableHeaderList: tableHeaderList,
          mjType: row.mjType,
          approvalStatus: this.approvalStatus
        }
        this.$nextTick(() => {
          if (getLastIndexOf(row.subTableName) == "F") {  //F 进入件详情
            this.jianDetailsOpen = true;
          } else { //进入卷详情 和项目详情
            this.juanDetailsOpen = true
          }
        })
      });
    },
    //关闭详情页面
    detailsHandleClose() {
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
    //关闭
    closeDelDialog() {
      this.$emit("closeDelDialog")
      this.imageUrl = ''
      this.isShow = false
      this.isShowButton = false
      this.tableList = []
    },
  }
}
</script>

<style lang="scss" scoped>

</style>
